﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using BP.OA;

namespace CCOA.App.NOTICE
{
    public partial class NoticeList : System.Web.UI.Page
    {
        #region //1.公共接口(Public Interface)
        //权限控制
        private string FuncNo = null;
        private DataTable GetNoticeCategorys()
        {
            string sql = "select No,Name from OA_NoticeCategory order by No";
            return BP.DA.DBAccess.RunSQLReturnTable(sql);
        }
        private DataTable GetAllPagedNoticeList(bool start)
        {
            string selCategory = this.rbl_Category.SelectedValue;
            string con = " where 1=1";

            if (selCategory != "0")
            {
                con += String.Format(" and A.FK_NoticeCategory='{0}'", selCategory);
            }
            //处理分级管理员
            if (BP.Web.WebUser.No != "admin")
            {
                con += String.Format(" and A.FK_UserNo='{0}'", BP.Web.WebUser.No);
            }
            //String.Format中第一个参数，是向其中加入一个
            string sSql = String.Format("select FK_UserNo as UserName,FK_Dept as Dept,A.OID,A.Title,B.Name as NoticeCategory,RDT,C.Lab as Importance,A.Importance as ImportLevel,NoticeSta,d.Lab as NoticeStaTitle,SetTop"
                                 + ",(select cast(count(*) as varchar) from OA_NoticeReader where FK_NoticeNo=A.OID and ReadTime<>'')"
                                 + "      +'/'+(select cast(count(*) as varchar) from OA_NoticeReader where FK_NoticeNo=A.OID)"
                                 + "         as ReadState"
                                 + ",case when NoticeSta=0 and GetDate() between StartTime and StopTime then cast(DateDiff(d,StopTime,GetDate()) as varchar)+'天后关闭'"
                                 + "        when NoticeSta=0 and GetDate() < StartTime then cast(DateDiff(d,StartTime,GetDate()) as varchar)+'天后打开'"
                                 + "        when NoticeSta=0 and GetDate() > StopTime then '已过期'+cast(DateDiff(d,GetDate(),StopTime) as varchar)+'天'"
                                 + "        when NoticeSta=1 then '手工打开'"
                                 + "        when NoticeSta=2 then '手工关闭'  End as PublishState"
                                 + ",case when NoticeSta=0 and GetDate() between StartTime and StopTime then 4"
                                 + "        when NoticeSta=0 and GetDate() < StartTime then 3"
                                 + "        when NoticeSta=0 and GetDate() > StopTime then 5"
                                 + "        when NoticeSta=1 then 1"
                                 + "        when NoticeSta=2 then 2 End as PublishStateFlag"
                                 + " from OA_Notice A"
                                 + " inner join OA_NoticeCategory B on B.No=A.FK_NoticeCategory"
                                 + " inner join Sys_Enum C on C.IntKey=A.Importance and C.EnumKey='Importance'"
                                 + " inner join Sys_Enum D on D.IntKey=A.NoticeSta and D.EnumKey='NoticeSta'"
                                 + con);
            if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
            {
                sSql = String.Format("select FK_UserNo as UserName,FK_Dept as Dept,A.OID,A.Title,B.Name as NoticeCategory,RDT,C.Lab as Importance,A.Importance as ImportLevel,NoticeSta,d.Lab as NoticeStaTitle,SetTop,"
                                                + "CONVERT(CONCAT((select count(*) from OA_NoticeReader where FK_NoticeNo=A.OID and ReadTime<>''),'/',(select count(*) from OA_NoticeReader where FK_NoticeNo=A.OID))"
                                                + " USING gb2312)  as ReadState"
                                                + ",case when NoticeSta=0 and CURDATE() between StartTime and StopTime then CONCAT(DateDiff(StopTime,CURDATE()),'天后关闭')"
                                                + "        when NoticeSta=0 and CURDATE() < StartTime then CONCAT(DateDiff(StartTime,CURDATE()),'天后打开')"
                                                + "        when NoticeSta=0 and CURDATE() > StopTime then CONCAT('已过期',DateDiff(CURDATE(),StopTime),'天')"
                                                + "        when NoticeSta=1 then '手工打开'"
                                                + "        when NoticeSta=2 then '手工关闭'  End as PublishState"
                                                + ",case when NoticeSta=0 and CURDATE() between StartTime and StopTime then 4"
                                                + "        when NoticeSta=0 and CURDATE() < StartTime then 3"
                                                + "        when NoticeSta=0 and CURDATE() > StopTime then 5"
                                                + "        when NoticeSta=1 then 1"
                                                + "        when NoticeSta=2 then 2 End as PublishStateFlag"
                                                + " from OA_Notice A"
                                                + " inner join OA_NoticeCategory B on B.No=A.FK_NoticeCategory"
                                                + " inner join Sys_Enum C on C.IntKey=A.Importance and C.EnumKey='Importance'"
                                                + " inner join Sys_Enum D on D.IntKey=A.NoticeSta and D.EnumKey='NoticeSta'"
                                                + con);
            }
            if (start)
            {
                int count = BP.OA.Main.GetPagedRowsCount(sSql);
                this.AspNetPager1.RecordCount = count;
                this.AspNetPager1.PageSize = 20;
                this.AspNetPager1.CurrentPageIndex = 1;
            }
            this.AspNetPager1.CustomInfoHTML = string.Format("当前第{0}/{1}页 共{2}条记录 每页{3}条", new object[] { this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageCount, this.AspNetPager1.RecordCount, this.AspNetPager1.PageSize });
            return BP.OA.Main.GetPagedRows(sSql, -1, "order by CAST(SetTop as datetime) desc,OID desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
        }
        private int ChangeNoticeState(int oid)
        {
            string sSql = String.Format("Update OA_Notice set NoticeSta=Case NoticeSta when 0 then 1 when 1 then 2 when 2 then 0 end where OID={0}", oid);
            int iR = BP.DA.DBAccess.RunSQL(sSql);
            return iR;
        }
        private int SetNoticeTop(int oid)
        {
            BP.OA.Notice notice = new BP.OA.Notice(oid);
            notice.SetTop = DateTime.Now;
            int iR = notice.Update();
            return iR;
        }
        private int CancelNoticeTop(int oid)
        {
            string sSql = String.Format("Update OA_Notice set SetTop='' where OID={0}", oid);
            int iR = BP.DA.DBAccess.RunSQL(sSql);
            return iR;
        }
        private int DeleteNotice(int oid)
        {
            string sSql = String.Format("Delete FROM OA_Notice where OID={0}", oid);
            int iR = BP.DA.DBAccess.RunSQL(sSql);
            return iR;
        }
        //公告状态方案
        private string TitleFormat_Auto_Pre = "color:forestgreen";
        private string TitleFormat_Auto_Between = "color:black";
        private string TitleFormat_Auto_After = "color:gray;text-decoration:line-through;";
        private string TitleFormat_Open = "color:darkgoldenrod";
        private string TitleFormat_Close = "color:gray;text-decoration:line-through;";
        #endregion

        #region //2.页面装载(Page Load)
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindCategory();
                this.BindData(true);
            }
        }
        //绑定数据        
        public void BindData(bool start)
        {
            DataTable dt = this.GetAllPagedNoticeList(start);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        /// <summary>
        /// 取得发布者为用户还是部门
        /// </summary>
        /// <param name="evalUser"></param>
        /// <param name="evalDept"></param>
        /// <returns></returns>
        public string GetPublish(object evalUser, object evalDept)
        {
            if (evalDept == Convert.DBNull || evalDept == null || String.IsNullOrEmpty(Convert.ToString(evalDept)))
                return BP.OA.GPM.GetUserName_By_No(Convert.ToString(evalUser));
            else
                return BP.OA.GPM.GetDeptName_By_No(Convert.ToString(evalDept));
        }
        public string GetImportLevel(object evalImportLevel)
        {
            if (evalImportLevel == Convert.DBNull) return null;
            String il = Convert.ToString(evalImportLevel);
            return String.Format("../../Images/Notice/Import{0}.png", il);
        }
        public string GetTitleFormatByState(object evalState)
        {
            if (evalState == null || evalState == Convert.DBNull) return String.Empty;
            int state = Convert.ToInt32(evalState);
            if (state == 3)
                return this.TitleFormat_Auto_Pre;
            else if (state == 4)
                return this.TitleFormat_Auto_Between;
            else if (state == 5)
                return this.TitleFormat_Auto_After;
            else if (state == 1)
                return this.TitleFormat_Open;
            else if (state == 2)
                return this.TitleFormat_Close;
            else
                return String.Empty;
        }
        public string GetRelativeTime(object evalTime)
        {
            return BP.OA.Main.GetTimeEslapseStr(Convert.ToDateTime(evalTime), null, null);
        }
        public void BindCategory()
        {
            DataTable dt = this.GetNoticeCategorys();
            BP.OA.UI.Dict.BindListCtrl(dt, this.rbl_Category, "Name", "No", null, "0#所有类型", "0");
        }
        #endregion

        #region //3.页面事件(Page Event)
        protected void ChangeState(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            int id = Convert.ToInt32(lb.CommandName);
            int iR = this.ChangeNoticeState(id);
            //5.（用户及业务对象）统计与状态

            //6.登记日志
            if (iR > 0)
            {
                //WX.Main.AddLog(WX.LogType.Default, String.Format("删除公告({0})成功！", id), "");
            }

            //7.返回处理结果或返回其它页面。
            if (iR > 0)
            {
                this.BindData(true);
            }
            else
            {
                BP.OA.Debug.Alert(this, "置顶失败！");
            }
        }
        protected void SetTop(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            int id = Convert.ToInt32(lb.CommandName);
            int iR = this.SetNoticeTop(id);
            //5.（用户及业务对象）统计与状态

            //6.登记日志
            if (iR > 0)
            {
                //WX.Main.AddLog(WX.LogType.Default, String.Format("删除公告({0})成功！", id), "");
            }

            //7.返回处理结果或返回其它页面。
            if (iR > 0)
            {
                this.BindData(false);
            }
            else
            {
                BP.OA.Debug.Alert(this, "置顶失败！");
            }
        }
        protected void CancelTop(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            int id = Convert.ToInt32(lb.CommandName);
            int iR = this.CancelNoticeTop(id);
            //5.（用户及业务对象）统计与状态

            //6.登记日志
            if (iR > 0)
            {
                //WX.Main.AddLog(WX.LogType.Default, String.Format("删除公告({0})成功！", id), "");
            }

            //7.返回处理结果或返回其它页面。
            if (iR > 0)
            {
                this.BindData(false);
            }
            else
            {
                BP.OA.Debug.Alert(this, "取消置顶失败！");
            }
        }
        //删除处理过程
        protected void Del(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            int id = Convert.ToInt32(lb.CommandName);
            //1.选择删除文件
            string sSql = String.Format("Select AttachFile from OA_Notice where OID={0}", id);
            BP.OA.Main.DeleteFiles_By_Sql(sSql);
            //2.再删除公告
            int iR = this.DeleteNotice(id);
            //3.最后删除阅读标志
            sSql = String.Format("Delete FROM OA_NoticeReader where FK_NoticeNo='{0}'", id);
            BP.DA.DBAccess.RunSQL(sSql);
            //5.（用户及业务对象）统计与状态

            //6.登记日志
            if (iR > 0)
            {
                //WX.Main.AddLog(WX.LogType.Default, String.Format("删除公告({0})成功！", id), "");
            }

            //7.返回处理结果或返回其它页面。
            if (iR > 0)
            {
                this.BindData(true);
            }
            else
            {
                BP.OA.Debug.Alert(this, "删除失败！");
            }
        }
        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            if (GridView1.Rows.Count > 0)
                GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            this.BindData(false);
        }
        protected void rbl_Category_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindData(true);
        }
        #endregion
    }
}